//
//  FoundViewController.m
//  TestApplication]
//
//  Created by dllo on 16/8/26.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "FoundViewController.h"
// Tool
#import "FoundFirstReusableView.h"
#import "TAMacro.h"
#import "UIImageView+WebCache.h"
#import "CDMNetTool.h"
#import "BaseButton.h"
#import "WebViewViewController.h"
// cell
#import "FoundSecondCollectionViewCell.h"
#import "HotSearchCollectionViewCell.h"
#import "FoundYouLikeCollectionViewCell.h"
#import "FoundTitleCollectionReusableView.h"
// model
#import "FoundFirstRootClass.h"
#import "FoundFirstData.h"
#import "FoundFirstCategorydoc.h"
#import "FoundFirstTimedoc.h"
#import "FoundFirstOrderdoc.h"
#import "FoundFirstToday.h"
#import "FoundFirstSunday.h"
#import "FoundFirstWeekend.h"
#import "FoundFirstSaturday.h"
#import "FoundFirstTomorrow.h"
#import "FoundFirstLastmonth.h"
#import "SmallIconView.h"
#import "FoundHotSearchRootClass.h"
#import "FoundyoulikeDic.h"
#import "DetailsViewController.h"
#import "FoundDetailsViewController.h"
#import "NearByViewController.h"
#import "CalendarViewController.h"
#import "TodayViewController.h"
#import "HotSearchViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
// LoginModel
#import "LoginDataData.h"
#import "LoginData.h"
#import "LoginRootClass.h"
#import "LoginDataRootClass.h"
#import "ClassifyViewController.h"


#define kFirstHeaderReuse @"firstHeaderReuse"
#define kTitleHeaderReuse @"titleHeaderResue"
#define kFoundSecondCollectionViewCellReuse @"SecondReuse"
#define kHotSeacrchCollectionViewCellResue @"HotReuse"
#define kYouLikeCollectionViewCellReuse @"YouLikeReuse"
@interface FoundViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *foundLayout;
@property (weak, nonatomic) IBOutlet UICollectionView *foundCollectionView;
@property (nonatomic, strong) FoundFirstRootClass *firstRootClass;
@property (nonatomic, strong) FoundHotSearchRootClass *hotSearchRootClass;
@property (nonatomic, strong) NSMutableArray<FoundYouLikeDic *> *foundYouLikeModelArr;
@property (nonatomic, strong) FoundYouLikeDic *youLikeDic;
@property (nonatomic, copy) NSString *mStr;

@property (nonatomic, strong) LoginRootClass *rootModel;
@property (nonatomic, strong) LoginDataRootClass *DataModel;

@end

@implementation FoundViewController{
    BOOL isLogin;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    // Do any additional setup after loading the view.
    self.foundYouLikeModelArr = [NSMutableArray array];
    [self configCollectionViewCell];
    [self handleFirstData];
    [self handleHotSearchData];
    [self handleYouLikeData];
   
    
}
#pragma mark - 添加用户信息


#pragma mark - 处理数据
// 处理第一部分的数据
- (void)handleFirstData {
    NSString *urlString = @"http://wanapi.damai.cn/filterpnew.json?platform=4&channel_from=m360_market&version=203004&source=10345";
    [CDMNetTool GET:urlString andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        self.firstRootClass = [FoundFirstRootClass modelWithDic:result];
        [self.foundCollectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败%@", error);
    }];
}
// 处理热门搜索的数据
- (void)handleHotSearchData {
    NSString *urlString = @"http://wanapi.damai.cn/p/hotword.json?&platform=4&channel_from=m360_market&version=203004&source=10345";
    
    [CDMNetTool GET:urlString andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
//        NSLog(@"请求成功%@", result);
        self.hotSearchRootClass = [FoundHotSearchRootClass modelWithDic:result];
        [self.foundCollectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败%@", error);
    }];
    
}
// 处理猜你喜欢的数据
- (void)handleYouLikeData {
    NSString *urlString = @"http://apprecommend.damai.cn/wireless-recommend/wan/cityhomepage?&visitorId=V4sA1MPjN70DAAg7G0LY5WTo&lon=121.54448&version=203004&lat=38.883461&cityId=110000";
    [CDMNetTool GET:urlString andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        
        for (NSDictionary *dic in result) {
            FoundYouLikeDic *youLikeDic = [[FoundYouLikeDic alloc] init];
            [youLikeDic setValuesForKeysWithDictionary:dic];
            [self.foundYouLikeModelArr addObject:youLikeDic];
        }
        //        NSLog(@"请求成功%@", result);
//        NSLog(@"%@", self.foundYouLikeModelArr);
        [self.foundCollectionView reloadData];
       
    
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败%@", error);
    }];

}
#pragma mark - 设置layout和Cell的注册等
- (void)configCollectionViewCell {
    // 设置layout属性
    self.foundLayout.minimumLineSpacing = 5;
    self.foundLayout.minimumInteritemSpacing = 5;
    self.foundLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    // cell注册
    [self.foundCollectionView registerNib:[UINib nibWithNibName:@"FoundSecondCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kFoundSecondCollectionViewCellReuse];
    [self.foundCollectionView registerNib:[UINib nibWithNibName:@"HotSearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kHotSeacrchCollectionViewCellResue];
    [self.foundCollectionView registerNib:[UINib nibWithNibName:@"FoundYouLikeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kYouLikeCollectionViewCellReuse];
    // 头视图注册
    [self.foundCollectionView registerClass:[FoundFirstReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kFirstHeaderReuse];
    [self.foundCollectionView registerClass:[FoundTitleCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kTitleHeaderReuse];

}
#pragma mark - collectionViewDataSource
#pragma mark - 返回分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}
#pragma mark - 返回item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    } else if (section == 1) {
        return 8;
    } else {
        return self.foundYouLikeModelArr.count;
    }
}
#pragma mark - 返回自定义cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        FoundSecondCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kFoundSecondCollectionViewCellReuse forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.imageView.image = [UIImage imageNamed:@"sign"];
        } else if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"nearby"];
        } else if (indexPath.row == 2) {
            cell.imageView.image = [UIImage imageNamed:@"calendar"];
        } else {
            cell.imageView.image = [UIImage imageNamed:@"todayTime"];
        }
        return cell;
    } else if (indexPath.section == 1) {
    HotSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kHotSeacrchCollectionViewCellResue forIndexPath:indexPath];
        NSString *buttonTitle = [NSString stringWithFormat:@"#%@", self.hotSearchRootClass.data[indexPath.row]];
        [cell.buttonData setTitle:buttonTitle forState:UIControlStateNormal];
    return cell;
    } else {
        FoundYouLikeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kYouLikeCollectionViewCellReuse forIndexPath:indexPath];
        FoundYouLikeDic *dic = self.foundYouLikeModelArr[indexPath.row];
    
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:dic.pic] placeholderImage:[UIImage imageNamed:@"project_bg_detail"]];
        cell.titlelabel.text = dic.title;
        cell.timestrLabel.text = dic.timestr;
        cell.venuenamelabel.text = dic.venuename;
        return cell;
    }
}
#pragma mark - 返回每个头视图的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 160);
    } else {
        return CGSizeMake(SCREEN_WIDTH, 30);
    }
}
#pragma mark - 返回每个item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CGFloat width = (SCREEN_WIDTH - 15) / 2;
        CGFloat height = 80;
        self.foundLayout.minimumLineSpacing = 5;
        self.foundLayout.minimumInteritemSpacing = 5;
        self.foundLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        return CGSizeMake(width, height);
    } else if (indexPath.section == 1) {
        self.foundLayout.minimumLineSpacing = 5;
        self.foundLayout.minimumInteritemSpacing = 5;
        self.foundLayout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
        CGFloat widht = (SCREEN_WIDTH - 5 * 5 - 10) / 4;
        CGFloat height = 20;
        return CGSizeMake(widht, height);
    } else {
        self.foundLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.foundLayout.minimumLineSpacing = 0;
        self.foundLayout.minimumInteritemSpacing = 0;
        CGFloat width = SCREEN_WIDTH;
        CGFloat height = 100;
        return CGSizeMake(width, height);
    }
}
#pragma mark - 返回自定义头视图或者尾视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        FoundFirstReusableView *reuseable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kFirstHeaderReuse forIndexPath:indexPath];
        
        reuseable.smallView.categoryArr = self.firstRootClass.data.CategoryDoc.mutableCopy;
        
        // block传递CollectionView的点击方法
        [reuseable.smallView selectIndexPath:^(NSIndexPath *indexPath) {
        self.hidesBottomBarWhenPushed = YES;
        ClassifyViewController *classifyVC = [[ClassifyViewController alloc] init];
        [self.navigationController pushViewController:classifyVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        }];
        
        return reuseable;
    } else {
        FoundTitleCollectionReusableView *reuseable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kTitleHeaderReuse forIndexPath:indexPath];
        if (indexPath.section == 1) {
            reuseable.labelTitle.text = @"热门搜索";
        } else if (indexPath.section == 2) {
            reuseable.labelTitle.text = @"猜你喜欢";
        }
        reuseable.backgroundColor = [UIColor whiteColor];
        return reuseable;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [user objectForKey:@"LoginData"];
            NSDictionary *dicM = [user objectForKey:@"LoginM"];
            self.DataModel = [LoginDataRootClass modelWithDic:dic];
            self.rootModel = [LoginRootClass modelWithDic:dicM];

            if (dic != nil && dicM != nil) {
                self.hidesBottomBarWhenPushed = YES;
                WebViewViewController *webVC = [[WebViewViewController alloc] init];
                NSString *urlString = @"http://dui.m.damai.cn/qiandao/users?jtwsmlogin=10";
                NSString *mStr = [NSString stringWithFormat:@"m=%@", self.rootModel.data.M];
                NSString *finalURLString = [urlString stringByAppendingFormat:@"&%@", mStr];
                webVC.webURLString = finalURLString;
                [self.navigationController pushViewController:webVC animated:YES];
                self.hidesBottomBarWhenPushed = NO;
                
            } else {
                LoginViewController *vc = [[LoginViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            
        } else if (indexPath.row == 1) {
           self.hidesBottomBarWhenPushed = YES;
            NearByViewController *nearByVC = [[NearByViewController alloc] init];
            [self.navigationController pushViewController:nearByVC animated:YES];
             self.hidesBottomBarWhenPushed = NO;
        } else if (indexPath.row == 2) {
            self.hidesBottomBarWhenPushed = YES;
            CalendarViewController *calendarVC = [[CalendarViewController alloc] init];
            [self.navigationController pushViewController:calendarVC animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        } else {
            self.hidesBottomBarWhenPushed = YES;
            TodayViewController *todayVC = [[TodayViewController alloc] init];
            [self.navigationController pushViewController:todayVC animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
    } else if (indexPath.section == 2) {
        if (self.foundYouLikeModelArr[indexPath.row].state == 2) {
            
      
            DetailsViewController *detailsVC = [DetailsViewController new];
            UINavigationController *detaNavi = [[UINavigationController alloc] initWithRootViewController:detailsVC];
        detailsVC.parm =  self.foundYouLikeModelArr[indexPath.row].ID;
            detaNavi.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

        [self presentViewController:detaNavi animated:YES completion:nil];
            
            
        } else if (self.foundYouLikeModelArr[indexPath.row].state == 3) {
        
            FoundDetailsViewController *foundDetailsVC = [[FoundDetailsViewController alloc] init];
            UINavigationController *foundNavi = [[UINavigationController alloc] initWithRootViewController:foundDetailsVC];
            foundDetailsVC.parm = self.foundYouLikeModelArr[indexPath.row].ID;
            foundNavi.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

            [self presentViewController:foundNavi animated:YES completion:nil];
        
        }
        
    } else {
        self.hidesBottomBarWhenPushed = YES;
        HotSearchViewController *hotVC = [[HotSearchViewController alloc] init];
        hotVC.searchString = self.hotSearchRootClass.data[indexPath.row];
        [self.navigationController pushViewController:hotVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
